import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/exam_history.dart';
import 'package:kxy_flutter_app/model/exam_question.dart';
import 'package:kxy_flutter_app/view/examination/do_review_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ExamHistoryListView extends StatefulWidget {
  final String cateId;
  ExamHistoryListView({Key key, this.cateId}) : super(key: key);

  @override
  _ExamHistoryListViewState createState() => _ExamHistoryListViewState();
}

class _ExamHistoryListViewState extends State<ExamHistoryListView> {
  RefreshController controller = new RefreshController();
  List<ExamHistory> examList = new List<ExamHistory>();
  int index = 1;
  int totalCount = 0;
  Future loadFuture;

  @override
  void initState() {
    super.initState();
    loadFuture = reload();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(title: Text('考试记录')),
      body: FutureBuilder(
        future: loadFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    if (examList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }
    return SmartRefresher(
      controller: controller,
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      child: examHistoryListWidget(),
      onLoading: () async {
        if (examList.length < totalCount) {
          await loadMore();
          controller.loadComplete();
        } else {
          controller.loadNoData();
        }
      },
      onRefresh: () async {
        await reload();
        controller.refreshCompleted();
      },
    );
  }

  Widget examHistoryListWidget() {
    return ListView(
      padding: EdgeInsets.symmetric(horizontal: 20),
      children: ListTile.divideTiles(tiles: examList.map((e) => examItemWidget(e)), context: context, color: Colors.black12).toList(),
    );
  }

  Widget examItemWidget(ExamHistory exam) {
    var formater = new DateFormat('yyyy-MM-dd');
    return ListTile(
      contentPadding: EdgeInsets.all(0),
      title: Text(
        exam.examName,
        style: TextStyle(
          fontSize: 16,
        ),
      ),
      subtitle: Text(
        formater.format(exam.submitPaperTime),
        style: TextStyle(
          fontSize: 12,
          color: Colors.black54,
        ),
      ),
      trailing: Text('${exam.score}分'),
      onTap: () async {
        var qlist = await loadQuesList(exam);
        if (qlist == null) return;
        Navigator.of(context).push(MaterialPageRoute(
          builder: (cxt) => DoReviewView(
            quesList: qlist,
            title: '考试记录',
            withQuesCard: true,
          ),
        ));
      },
    );
  }

  Future reload() async {
    index = 1;
    totalCount = 0;
    examList.clear();
    await loadMore();
  }

  Future loadMore() async {
    var res = await Http.instance.post('/exam-app/exam/userExamRecord', params: {
      'cateId': widget.cateId,
      'userId': Auth.instance.userId,
      'page': index,
      'limit': 20,
    });

    if (res.code == 200) {
      setState(() {
        totalCount = res.data['totalCount'];
        (res.data['list'] as List).forEach((item) {
          var examHistory = ExamHistory.fromJson(item);
          examList.add(examHistory);
        });
        index++;
      });
    }
  }

  Future<List<Question>> loadQuesList(ExamHistory exam) async {
    var res = await Http.instance.post('/exam-app/exam/userExamRecordQuesList', params: {
      'examId': exam.examId,
      'userId': Auth.instance.userId,
    });

    if (res.code == 200) {
      return (res.data as List).map((e) => Question.fromJson(e)).toList();
    } else {
      Fluttertoast.showToast(msg: res.msg);
      return null;
    }
  }

  Future<bool> uncollect(String quesId) async {
    var res = await Http.instance.post('/exam-app/coll/unCollQues', params: {
      'quesId': quesId,
      'userId': Auth.instance.userId,
    });
    if (res.code == 200) {
      return true;
    }
    return false;
  }
}
